import sys
import os
from typing import List
import ast


def check_code_type(statement: str):
    """判断语句是否是赋值语句"""
    try:
        # 将语句解析为抽象语法树
        tree = ast.parse(statement)
    # 语法错误，不是有效的 Python 语句
    except Exception as e:
        # 捕获异常并打印出错信息
        print("语法错误：", e)
        return -1

    if statement.count('\n') > 1:
        return 1

    # 遍历语法树，查找赋值语句
    for node in ast.walk(tree):
        if isinstance(node, ast.Assign):
            # 找到了赋值语句
            return 1

    # 没有找到赋值语句
    return 0


# 本文件的真实路径
real_dir = os.path.dirname(os.path.realpath(__file__))

extension_path = os.path.abspath(os.path.join(real_dir, '../extensions'))
share_path = os.path.abspath(os.path.join(real_dir, '../share'))

sys.path.append(extension_path)
sys.path.append(share_path)


class RunnerMod:
    def __init__(self):
        self.variable_pool = {}
        self.exten_tools_classes = {}

    def run_script(self, script):
        check_ret = check_code_type(script)
        if check_ret == -1:
            return ''
        try:
            exec(script, self.variable_pool, None)
            return ''
        except Exception as e:
            # 捕获异常并打印出错信息
            print("出错了：", e)

    def run_cmd(self, cmd):
        check_ret = check_code_type(cmd)
        if check_ret == -1:
            return ''

        if check_ret == 0:
            try:
                result = eval(cmd,self.variable_pool)
                if result is None:
                    result = ''
                result = str(result)
                return result
            except Exception as e:
                # 捕获异常并打印出错信息
                print("出错了：", e)
        else:
            try:
                exec(cmd, self.variable_pool, None)
                return ''
            except Exception as e:
                # 捕获异常并打印出错信息
                print("出错了：", e)


    def get_variables(self):
        return self.variable_pool


    def build_extend_tools(self, tools_import_codes: List[str]):
        exec('\n'.join(tools_import_codes), None, self.exten_tools_classes)
        return self.exten_tools_classes